const request = require('../../../utils/api.js')
const {
  $Toast
} = require('../../../dist/base/index');

Page({

  /**
   * 页面的初始数据
   */
  data: {

    fileType: 2, //2文档打印，1照片打印
    fileIds: [], //文件id
    startPage: 1, //开始页
    endPage: 1, //结束页
    duplex: false, //双面打印
    printType: 0, //打印类型
    copies: 1, //份数
    printLater: false, //是否预约打印
    colorPrint: false, //是否彩印
    //verticalPrint:'',此参数废弃
    source: 3, //来源，3小程序
    printCode: '',

    docList: [],
    fileName: "",
    qiniuUrl: '',
    //fileId: '',
    tagSelect: true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    if (options.fileFrom == "library") {

      this.setData({
        // "docList": options.path, 
        fileName: options.fileName,
        qiniuUrl: options.qiniuUrl,
        fileIds: [parseInt(options.fileId)],
        fileFrom: options.fileFrom,
        tagSelect: false,
        totalPage: parseInt(options.totalPage),
        endPage: parseInt(options.totalPage)
      })

    } else {
      this.setData({
        // "docList": options.path, 
        fileName: options.fileName,
        qiniuUrl: options.qiniuUrl,
        fileIds: [parseInt(options.fileId)],
        fileFrom: options.fileFrom,
        tagSelect: true,
        totalPage: parseInt(options.totalPage)
      })
    }
    if (options.fileName != '' && options.fileName != null) {
      this.getPrintType();
    }



  },

  radioChange: function(e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value)

    var items = this.data.items;
    for (var i = 0, len = items.length; i < len; ++i) {
      items[i].checked = items[i].value == e.detail.value
    }

    this.setData({
      items: items
    });
  },

  //组件加减值
  addNumber: function() {
    const adNumber = this.data.printNumber + 1;
    this.setData({
      copies: adNumber
    })
  },

  reduceNumber: function() {
    const reNumber = this.data.printNumber - 1;
    this.setData({
      copies: reNumber
    })
  },


  //打印
  printDoc: function(e) {

    var that = this

    if (that.data.printCode == '' || that.data.printCode == null) {
      $Toast({
        content: '请输入打印码',
        type: 'warning'
      });
    }

    //验证页数与单双面打印的正取性
    if (that.data.duplex === true && parseInt(that.data.totalPage) === 1) {

      $Toast({
        content: '单页无法选择双面打印',
        type: 'warning'
      });
    }

    //首先验证数据，打印码是否正确

    const data = {
      url: '/v3/print/print_code',
      method: 'POST',
      param: {
        'fileType': 2,
        'fileIds': that.data.fileIds, //文件id
        'startPage': that.data.startPage, //开始页
        'endPage': that.data.endPage, //结束页
        'duplex': that.data.duplex, //双面打印
        'printType': that.data.printType, //打印类型
        'copies': that.data.copies, //份数
        'printLater': that.data.printLater, //是否预约打印
        'colorPrint': that.data.colorPrint, //是否彩印
        'source': 3, //来源，3小程序
        'printCode': that.data.printCode, //设备显示的打印码
      }
    }
    console.log(data, "HMS")
    request(data).then(res => {
      console.log(res, "Santiago")
      if (res.data.code === 200) {

        var printID = res.data.data.printId;

        if (res.data.data.printFee === 0) {
          //监听打印状态，循环或者定时器实现

          const dataForMonitor = {
            url: '/v3/print/print_status',
            method: 'POST',
            param: {
              'printId': printID,

            }
          }
          request(dataForMonitor).then(res => {
            console.log(res, "MAOMAO")
            if (res.data.code === 200) {
              wx.showToast({
                title: '打印成功',
                icon: 'success',
                duration: 1000,
                success(res) {
                  // 成功后跳转至完成界面
                  wx.navigateTo({
                    url: '../' + e.currentTarget.dataset.page + '/' + e.currentTarget.dataset.page
                  })
                }

              })
            }
          })
        } else {
          wx.requestPayment({
            timeStamp: res.data.data.timeStamp,
            nonceStr: res.data.data.nonceStr,
            package: res.data.data.package,
            signType: res.data.data.signType,
            paySign: res.data.data.paySign,
            success(res) {
              wx.showLoading({
                title: '打印中···',
              })

              var a = setInterval(function () {
                //循环执行代码 
                console.log(res, "茂")
                const dataForMonitor = {
                  url: '/v3/print/print_status',
                  method: 'POST',
                  param: {
                    'printId': printID,
                  }
                }
                request(dataForMonitor).then(res => {
                  console.log(res, "MAOMAO")
                  if (res.data.code === 200) {

                    //停止打印条件
                      if (res.data.stop == false) {
                        clearInterval(a)
                        wx.hideLoading()
                      }
                        // 成功后跳转至完成界面
                        wx.navigateTo({
                          url: '../' + e.currentTarget.dataset.page + '/' + e.currentTarget.dataset.page
                        })
                  }
                })
               
              }, 1000)

             
             

            },
            fail(res) {

            }
          })
        }

        //发起支付，应该加上条件判断


      } else if (res.data.code === 401) {
        $Message({
          content: '页面过期',
          type: 'error'
        })
      }
    })


    // 成功后跳转至完成界面
    // wx.navigateTo({
    //   url: '../' + e.currentTarget.dataset.page + '/' + e.currentTarget.dataset.page
    // })
  },


  //pdf文件预览
  pdfView: function() {
    var that = this;
    wx.downloadFile({
      url: that.data.qiniuUrl,
      success: function(res) {
        console.log(res)
        var path = res.tempFilePath //返回的文件临时地址，用于后面打开本地预览所用
        wx.openDocument({
          filePath: path,
          success: function(res) {
            console.log('打开成功');
          }
        })
      },
      fail: function(res) {
        console.log(res);
      }
    })
  },

  //获取单双面的值
  duplexChange: function(e) {
    var that = this;
    that.setData({
      duplex: Boolean(e.detail.value)
    })
  },

  //获取彩印的值
  colorChange: function(e) {
    var that = this;
    that.setData({
      colorPrint: Boolean(e.detail.value)
    })
  },

  //获取打印范围
  getStartPage: function(e) {
    var that = this;
    that.setData({
      startPage: Number(e.detail.value)
    })
  },
  getEndPage: function(e) {
    var that = this;
    that.setData({
      endPage: Number(e.detail.value)
    })
  },

  //获取打印码
  getPrintCode: function(e) {
    var that = this;
    that.setData({
      printCode: e.detail.value
    })
  },

  //根据文件名获取文件类型的值
  getPrintType: function() {
    var that = this;
    var fileExt = that.data.fileName.replace(/.+\./, "");
    var type = that.data.fileName.substring(that.data.fileName.lastIndexOf('.') + 1);

    if (type === "doc" || type === "docx") {
      that.setData({
        printType: 210
      })
    }

    if (type === "xls" || type === "xlsx") {
      that.setData({
        printType: 211
      })
    }
    if (type === "ppt" || type === "pptx") {
      that.setData({
        printType: 212
      })
    }
    if (type === "pdf") {
      that.setData({
        printType: 213
      })
    }

    if (type === "txt") {
      that.setData({
        printType: 214
      })
    }

  },




  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})